<template>
  <div class="complaint-table-wrapper">
    <div class="system-setting-wrapper">
      <div></div>
      <div @click="settingVisiable = true" class="system-setting">
        <div class="icon">
          <Setting />
        </div>
        <span style="font-size: 16px;">配置链接</span>
      </div>
    </div>
    <div class="continer-wrapper">
      <div class="header">
        <div class="title">投诉内容</div>
      </div>
      <div class="seach-wrapper">
        <div class="search-content">
          <div class="condition-wrapper">
            <span>投诉原因：</span>
            <el-tree-select clearable v-model="reasonId" placeholder="请选择" :data="complaintData"
              :render-after-expand="false" style="width: 200px" />
          </div>
          <div class="condition-wrapper">
            <span>处理状态：</span>
            <el-select clearable v-model="processStatus" placeholder="请选择" style="width: 200px">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="condition-wrapper">
            <span>投诉方查询：</span>
            <el-input clearable v-model="phone" style="width: 200px" placeholder="联系方式" />
          </div>
        </div>
        <el-button :icon="Search" style="background: #0152d9;border-color: #0152d9;" type="primary"
          @click="queryList">搜索</el-button>
      </div>
      <el-table v-loading="tableLoading" :data="tableData" style="height: 65vh;">
        <el-table-column prop="id" label="序号" width="180" />
        <el-table-column prop="reasonName" label="投诉原因" width="180" />
        <el-table-column prop="imageKey" label="附件图片">
          <template #default="scope">
            <img style="width: 30px;" @click="handleShowImg(scope.row.imageKey)" src="../../assets/lookImg.png" />
          </template>
        </el-table-column>
        <el-table-column prop="content" label="投诉内容" />
        <el-table-column prop="phone" label="联系方式" />
        <el-table-column prop="createTime" label="投诉时间">
          <template #default="scope">
            {{ dayjs(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column prop="processStatus" label="处理状态">
          <template #default="scope">
            {{ scope.row.processStatus === 0 ? "待处理" : "已处理" }}
          </template>
        </el-table-column>
        <el-table-column prop="processPoint" label="处理意见" />
        <el-table-column prop="address" label="操作">
          <template #default="scope">
            <el-button @click="handleFinish(scope.row.id)">处理</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20]" background
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="处理" width="500" :before-close="handleClose">
      <el-input v-model="processPoint" type="textarea" placeholder="请输入处理意见" />
      <div style="display: flex;align-items: center;justify-content: center; margin-top: 20px;">
        <el-button style="width: 100px; height: 32px;background: #0152d9;border-color: #0152d9;"
          @click="confirmProcessPoint" type="primary">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="settingVisiable" title="配置投诉链接" width="500" :before-close="handleSettingClose">
      <div>{{ originUrl }}{{ corpId }}</div>
      <div style="display: flex;align-items: center;justify-content: center; margin-top: 20px;">
        <el-button style="width: 100px; height: 32px;background: #0152d9;border-color: #0152d9;" @click="copyLink"
          type="primary">复制</el-button>
      </div>
    </el-dialog>
    <el-image-viewer v-if="showPreview" lazy :url-list="imageKeys" :preview-teleported="true"
      @close="showPreview = false" />
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { getRecordList, processFinish, getWechatUser, getComplaintTree } from "../../api/index";
import dayjs from "dayjs";
import { useRoute } from "vue-router";
import clipboard3 from "vue-clipboard3";
import { Setting, Search } from '@element-plus/icons-vue'

const route = useRoute();
const tableData = ref([]);
const phone = ref("");
const total = ref(0);
const corpId = ref("");
const pageSize = ref(10);
const currentPage = ref(1);
const complaintData = ref([])
const reasonId = ref('')
const processStatus = ref('')
const currentId = ref('')
const dialogVisible = ref(false)
const processPoint = ref('')
const showPreview = ref(false);
const imageKeys = ref([]);
const originUrl = ref('');
const settingVisiable = ref(false);
const tableLoading = ref(false);
const statusOptions = [
  {
    value: '0',
    label: '待处理',
  },
  {
    value: '1',
    label: '已处理',
  },
]

const copyLink = async () => {
  const { toClipboard } = clipboard3();
  try {
    await toClipboard(`${originUrl.value}${corpId.value}`);
    console.log('复制成功!')
  } catch (error) {
    console.log("复制失败!")
  }
  settingVisiable.value = false
}
const handleSettingClose = () => {
  settingVisiable.value = false;
}

const handleShowImg = (imgs) => {
  imageKeys.value = imgs;
  showPreview.value = true;
}

const handleClose = () => {
  dialogVisible.value = false
  currentId.value = '';
  processPoint.value = '';
}

const confirmProcessPoint = () => {
  processFinish({ id: currentId.value, processPoint: processPoint.value }).then((res) => {
    handleClose();
    queryList();
  });
}

const addLevelToData = (data) => {
  // 遍历当前层级的每个对象
  data.forEach(item => {
    // 添加 level 属性
    item.children = item.subReasonList;
    item.label = item.name;
    item.value = item.id;

    // 如果有子列表，递归处理子层级（level + 1）
    if (item.subReasonList && item.subReasonList.length > 0) {
      addLevelToData(item.subReasonList);
    }
  });
}

const queryComplaintTree = async () => {
  getComplaintTree({ corpId: res?.data?.data?.corpId || localStorage.getItem('corpId') }).then(res => {
    const data = res.data.data;
    addLevelToData(data);
    complaintData.value = data;
  })
}
queryComplaintTree()

const queryWechatUser = () => {
  getWechatUser({ code: route.query.code }).then((res) => {
    corpId.value = res?.data?.data?.corpId || localStorage.getItem('corpId');
    localStorage.setItem("corpId", corpId.value);
  }).finally(() => {
    queryList();
  })
};
queryWechatUser();

const queryList = () => {
  tableLoading.value = true;
  getRecordList({
    current: currentPage.value,
    size: pageSize.value,
    phone: phone.value,
    reasonId: reasonId.value,
    processStatus: processStatus.value,
    corpId:
      localStorage.getItem("corpId") || '',
  }).then((res) => {
    const data = res.data.data.complaintList;
    data.forEach(element => {
      element.imageKey = element.imageKey.split(",");
      element.imageKey.forEach((item, index) => {
        element.imageKey[index] = "https://welkin-1326777323.cos.ap-beijing.myqcloud.com/" + item;
      })
    });
    tableLoading.value = false;
    tableData.value = data;
    total.value = res.data.data.total;
  });
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryList();
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  queryList();
}

const handleFinish = (id) => {
  currentId.value = id;
  dialogVisible.value = true;
};

onMounted(() => {
  originUrl.value = `${window.location.origin}/complaint/#/complaintsList?appid=`
});
</script>
<style lang="less" scoped>
.complaint-table-wrapper {
  width: 100%;
  height: 100vh;
  background-color: #ededed;


  .system-setting-wrapper {
    background: #0152d9;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0px 20px;

    .system-setting {
      color: #fff;
      display: flex;
      align-items: center;

      .icon {
        width: 20px;
        height: 20px;
        margin-right: 8px;
      }
    }
  }

  .continer-wrapper {
    margin: 30px 12px 0px 12px;
    background-color: #fff;
    padding: 24px;
    overflow: hidden;

    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .title {
        font-weight: 700;
        margin-bottom: 10px;
        font-size: 20px;
      }
    }

    .seach-wrapper {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .search-content {
        display: flex;
        align-items: center;
      }

      .condition-wrapper {
        display: flex;
        align-items: center;
        margin-right: 30px;
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: flex-end;
      margin: 10px 0px;
    }
  }
}
</style>